/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sda.levelup.ciphers;

import java.io.IOException;

/**
 *
 * @author Дима
 */
public class Caesar implements Icipher
{

    private String alphabet()
    {
        String alphabet = "";
        for (int i = 0; i < 26; i++)
        {
            alphabet += (char) ('a' + i);
        }
        return alphabet;
    }

    public String encrypt(String input, String keyT)
    {
        int key = Integer.parseInt(keyT);
        String abc = alphabet();
        char[] mas = input.toCharArray();
        for (int i = 0; i < mas.length; i++)
        {
            if (abc.contains(Character.toString(Character.toLowerCase(mas[i]))))
            {
                int shift = abc.indexOf(Character.toLowerCase(mas[i]));
                char repl = abc.charAt((shift + key) % 26);
                if (Character.getType(mas[i]) == Character.UPPERCASE_LETTER)
                {
                    mas[i] = Character.toUpperCase(repl);
                }
                else
                {
                    mas[i] = repl;
                }
            }

        }
        String result = new String(mas);
        return result;
    }

    public String decrypt(String input, String keyT)
    {
        int key = Integer.parseInt(keyT);
        String abc = alphabet();
        char[] mas = input.toCharArray();
        for (int i = 0; i < mas.length; i++)
        {
            if (abc.contains(Character.toString(Character.toLowerCase(mas[i]))))
            {
                int shift = abc.indexOf(Character.toLowerCase(mas[i]));
                char repl = abc.charAt((shift + 260 - key) % 26);
                if (Character.getType(mas[i]) == Character.UPPERCASE_LETTER)
                {
                    mas[i] = Character.toUpperCase(repl);
                }
                else
                {
                    mas[i] = repl;
                }
            }

        }
        String result = new String(mas);
        return result;
    }
}
